import { NextApiRequest, NextApiResponse } from "next";

const OpenAI = require("openai");
const apiKey = process.env.AICHATAPI_SECRET;
const myclient = new OpenAI({
    apiKey: "sk-HKwsCbJcuK8rODncAXYLNtRLCDclRF4ERbp8JYaKgh3hNNdW",
    baseURL: "https://api.moonshot.cn/v1",
});

let myhistory = [{ "role": "system", "content": "你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。" }];

async function chat(prompt) {
    myhistory.push({
        role: "user", content: prompt
    });
    const completion = await myclient.chat.completions.create({
        model: "moonshot-v1-8k",
        messages: myhistory,
    });
    myhistory = myhistory.concat(completion.choices[0].message);
    return completion.choices[0].message.content;
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    // 设置 CORS 头部
    res.setHeader('Access-Control-Allow-Origin', '*'); // 允许所有来源
    if (req.method === "POST") {
        try {
            console.log("这是输入信息：", req.body.message);
            const result = await chat(req.body.message);
            console.log("这是输出结果：", result);
            res.status(200).json({ AichatReplyMessage: result });
        } catch (error) {
            res.status(500).json({ message: 'AiChat query error', error });
        }
    } else {
        res.send({ message: 'private api' });
    }
}
